<template>
  <div class="param-group-form">
    <!-- 动态表格模式 -->
    <div v-if="allowDynamicRows" class="dynamic-table">
      <div class="table-header">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          @click="addRow"
          :disabled="localData.rows.length >= maxRows"
        >
          添加行 ({{ localData.rows.length }}/{{ maxRows }})
        </el-button>
      </div>

      <el-table
        :data="localData.rows"
        border
        size="mini"
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>

        <el-table-column
          v-for="param in safeParams"
          :key="param.paramId || param.paramCode"
          :label="getParamLabel(param)"
          :width="param.columnWidth || 120"
          min-width="100"
        >
          <template slot-scope="scope">
            <param-input
              :param="param"
              :value="scope.row[param.paramCode]"
              :table-mode="true"
              :row-index="scope.$index"
              @change="handleRowChange(scope.$index, param.paramCode, $event)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRow(scope.$index)"
              :disabled="localData.rows.length <= 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 普通表单模式 -->
    <div v-else class="normal-form">
      <el-form
        :model="localData.params"
        label-width="120px"
        size="mini"
        class="param-form"
      >
        <el-row :gutter="16">
          <el-col
            v-for="param in safeParams"
            :key="param.paramId || param.paramCode"
            :span="getColumnSpan(param)"
          >
            <param-input
              :param="param"
              :value="localData.params[param.paramCode]"
              @change="handleParamChange(param.paramCode, $event)"
            />
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import ParamInput from './ParamInput.vue'

export default {
  name: 'ParamGroupForm',
  components: { ParamInput },
  props: {
    params: {
      type: Array,
      default: () => []
    },
    data: {
      type: Object,
      default: () => ({})
    },
    groupPath: {
      type: String,
      required: true
    },
    allowDynamicRows: {
      type: Boolean,
      default: false
    },
    maxRows: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      localData: {
        params: {},
        rows: []
      }
    }
  },
  computed: {
    safeParams() {
      return (this.params || []).filter(param => param && param.paramCode)
    },
    getColumnSpan() {
      return (param) => {
        const width = param.columnWidth || 120
        return width >= 200 ? 12 : width >= 150 ? 8 : 6
      }
    },
    // 从 groupPath 解析组索引
    parsedGroupIndex() {
      const match = this.groupPath.match(/groups\.(\d+)/)
      return match ? parseInt(match[1]) : null
    },
    // 从 groupPath 解析子组索引
    parsedChildGroupIndex() {
      const match = this.groupPath.match(/childGroups\.(\d+)/)
      return match ? parseInt(match[1]) : null
    }
  },
  watch: {
    data: {
      handler(newData) {
        this.updateLocalData(newData)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
 * 创建新行数据 - 修复版本
 */
createNewRow() {
      const newRow = {}
      this.safeParams.forEach(param => {
        if (param.isMultiMeasure && param.multiMeasureCount > 1) {
          newRow[param.paramCode] = Array.from(
            { length: param.multiMeasureCount },
            () => ({ value: '', isValid: true, message: '' })
          )
          console.log(`[创建多测次参数] ${param.paramCode}: ${param.multiMeasureCount}次`)
        } else {
          newRow[param.paramCode] = { value: '', isValid: true, message: '' }
        }
      })
      
      console.log('[创建新行]', newRow)
      return newRow
    },
    updateLocalData(data) {
      if (!data) return
      
      if (this.allowDynamicRows) {
        this.localData.rows = data.rows || []
        if (this.localData.rows.length === 0) {
          this.addRow()
        }
      } else {
        this.localData.params = data.params || {}
      }
    },

    getParamLabel(param) {
      let label = param.paramName || param.paramCode || '未命名参数'
      if (param.unit) label += ` (${param.unit})`
      if (param.isMultiMeasure && param.multiMeasureCount > 1) {
        label += ` [${param.multiMeasureCount}次]`
      }
      return label
    },

    handleParamChange(paramCode, value) {
      this.$set(this.localData.params, paramCode, value)
      this.emitDataChange()
      
      // 触发相关计算 - 修复：传递正确的上下文
      const param = this.safeParams.find(p => p.paramCode === paramCode)
      if (param) {
        this.triggerCalculation(null, param)
      }
    },

    /**
     * 处理行参数变化 - 修复版本
     */
    handleRowChange(rowIndex, paramCode, value) {
      if (this.localData.rows[rowIndex]) {
        console.log(`[行参数变化] 行${rowIndex}参数${paramCode}:`, value)
        
        this.$set(this.localData.rows[rowIndex], paramCode, value)
        
        // 触发相关计算
        const param = this.safeParams.find(p => p.paramCode === paramCode)
        if (param) {
          this.triggerCalculation(rowIndex, param)
        }
        
        this.emitDataChange()
      }
    },

    triggerCalculation(rowIndex, changedParam) {
      const dependentCalculations = this.safeParams.filter(p => 
        p.paramType === 'calculation' && 
        p.dependencies && 
        p.dependencies.includes(changedParam.paramCode)
      )

      if (dependentCalculations.length > 0) {
        // 构建计算上下文 - 修复：确保传递所有必要的索引
        const calculateData = {
          groupIndex: this.parsedGroupIndex,
          rowIndex: rowIndex !== null ? rowIndex : undefined,
          changedParamCode: changedParam.paramCode,
          dependentCalculations
        }

        // 如果是嵌套组，添加子组索引
        if (this.parsedChildGroupIndex !== null) {
          calculateData.childGroupIndex = this.parsedChildGroupIndex
        }

        console.log('触发计算:', calculateData)
        this.$emit('calculate', calculateData)
      }
    },

    addRow() {
      if (this.localData.rows.length < this.maxRows) {
        const newRow = {}
        this.safeParams.forEach(param => {
          if (param.isMultiMeasure && param.multiMeasureCount > 1) {
            newRow[param.paramCode] = Array.from(
              { length: param.multiMeasureCount },
              () => ({ value: '', isValid: true, message: '' })
            )
          } else {
            newRow[param.paramCode] = { value: '', isValid: true, message: '' }
          }
        })
        this.localData.rows.push(newRow)
        this.emitDataChange()
      }
    },

    removeRow(index) {
      if (this.localData.rows.length > 1) {
        this.localData.rows.splice(index, 1)
        this.emitDataChange()
      }
    },

    emitDataChange() {
      const data = this.allowDynamicRows
        ? { rows: [...this.localData.rows] }
        : { params: { ...this.localData.params } }

      this.$emit('data-change', {
        groupPath: this.groupPath,
        data
      })
    }
  }
}
</script>
<style scoped>
.param-group-form {
  width: 100%;
}

.dynamic-table {
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 12px;
}

.normal-form {
  width: 100%;
}

.param-form {
  width: 100%;
}
</style>